package za.co.EYEWTKAH.jmsProjects.openJmsPlugin;

import java.io.IOException;
import java.net.ServerSocket;

import org.apache.maven.plugins.annotations.Parameter;

import za.co.EYEWTKAH.jmsProjects.openJmsEmbedded.StartJMS;

import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger;

public class OpenJmsServer extends AbstractServer {

    @Parameter
    private String openJmsHome;

    @Parameter
    private Boolean createHome;

    private boolean isStarted = false;

    @Override
    public void configure(String name, Object value, Logger logger) {
        if ("openJmsHome".equals(name)) {
            openJmsHome = (String) value;
        }

        if ("createHome".equals(name)) {
            createHome = (Boolean) value;
        }

    }

    @Override
    public void start(Logger logger) {
        try {
            StartJMS.startJMSServer(openJmsHome, createHome, logger);
        } catch (Exception e) {
            isStarted = false;
            throw new RuntimeException(e);
        }

        waitForPort(1099);
        waitForPort(1098);
        isStarted = true;

    }

    private void waitForPort(int port) {

        boolean portTaken = false;
        while (!portTaken) {
            ServerSocket socket = null;
            try {
                socket = new ServerSocket(port);
            } catch (IOException e) {
                portTaken = true;
            } finally {
                if (socket != null)
                    try {
                        socket.close();
                    } catch (IOException e) { /* e.printStackTrace(); */
                    }
            }
        }

    }

    @Override
    public boolean isStarted(Logger logger) {
        return isStarted;
    }

    @Override
    public void stop(Logger logger) {
    	try {
			StartJMS.stop(openJmsHome, createHome, logger);
		} catch (Exception e) {
			throw new RuntimeException("Failed to stop openjms server", e);
		}
        isStarted = false;
    }

    @Override
    public boolean isStopped(Logger logger) {
        return !isStarted;
    }

}
